package com.nettest.service.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.nettest.entity.system.Role;
import com.nettest.entity.system.Staff;
import com.nettest.service.system.StaffService;
@Service("securityService")
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private StaffService usersDao;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Staff users = this.usersDao.loadStaff(username);
		if (users == null) {
			throw new UsernameNotFoundException(username);
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);

		users.setAuthorities(grantedAuths);

		return users;
	}

	// 取得用户的权限
	private Set<GrantedAuthority> obtionGrantedAuthorities(Staff user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		Set<Role> roles = user.getRoles();

		for (Role role : roles) {
			authSet.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
		}
		return authSet;
	}

	public StaffService getUsersDao() {
		return usersDao;
	}

	public void setUsersDao(StaffService usersDao) {
		this.usersDao = usersDao;
	}
}
